<template>
  <div class="visitor-index">
    <a-row class="aRow-wrapper" :gutter="12">
      <a-col class="listContent-wrapper" :span="24">
        <div class="title-wrapper-box">
          <crumbs :content="content" :updateTime="false"></crumbs>
        </div>
        <div class="l-w_content">
          <div class="l-w_c_content">
            <div class="pageInfo">
              <div class="tab-info">
                <a-anchor
                  :affix="false"
                  :bounds="400"
                  class="anchor-wrapper"
                  :get-current-anchor="getCurrentAnchor"
                  :getContainer="getContainerBack"
                >
                  <a-anchor-link
                    :href="`#${item.title}`"
                    :title="item.name"
                    v-for="(item, index) in tabList"
                    :key="index"
                  />
                </a-anchor>
              </div>
              <div class="right-content">
                <div>
                  <div id="basic-anchor">
                    <div class="common-title">
                      <div class="icon"></div>
                      <div class="content">基础信息</div>
                    </div>
                    <div class="content-wrapper">
                      <div class="flex">
                        <div class="info-wrap f1">
                          <div class="label common-lable">患者姓名</div>
                          <div class="value common-value">{{ wbMentalPatientBean.name || '暂无' }}</div>
                        </div>
                        <div class="info-wrap f1">
                          <div class="label common-lable">身份证号</div>
                          <div class="value common-value">{{ wbMentalPatientBean.idCard || '暂无' }}</div>
                        </div>
                      </div>
                      <div class="flex">
                        <div class="info-wrap f1">
                          <div class="label common-lable">性别</div>
                          <div class="value common-value">{{ wbMentalPatientBean.sex || '暂无' }}</div>
                        </div>
                        <div class="info-wrap f1">
                          <div class="label common-lable">年龄</div>
                          <div class="value common-value">
                            {{ wbMentalPatientBean.age || '暂无' }}
                          </div>
                        </div>
                      </div>

                      <div class="flex">
                        <div class="info-wrap f1">
                          <div class="label common-lable">民族</div>
                          <div class="value common-value">{{ wbMentalPatientBean.nation || '暂无' }}</div>
                        </div>
                        <div class="info-wrap f1">
                          <div class="label common-lable">血型</div>
                          <div class="value common-value">
                            {{ wbMentalPatientBean.bloodType || '暂无' }}
                          </div>
                        </div>
                      </div>

                      <div class="flex">
                        <div class="info-wrap f1">
                          <div class="label common-lable">精神障碍等级</div>
                          <div class="value common-value">{{ wbMentalPatientBean.patientLevel || '暂无' }}</div>
                        </div>
                        <div class="info-wrap f1">
                          <div class="label common-lable">判定时间</div>
                          <div class="value common-value">{{ wbMentalPatientBean.judgmentTime || '暂无' }}</div>
                        </div>
                      </div>

                      <div class="flex">
                        <div class="info-wrap f1">
                          <div class="label common-lable">判定单位</div>
                          <div class="value common-value">{{ wbMentalPatientBean.judgmentUnit || '暂无' }}</div>
                        </div>
                        <div class="info-wrap f1">
                          <div class="label common-lable">责任医疗机构</div>
                          <div class="value common-value">
                            {{ wbMentalPatientBean.responsibleOrganization || '暂无' }}
                          </div>
                        </div>
                      </div>

                      <div class="flex">
                        <div class="info-wrap f1">
                          <div class="label common-lable">详细地址</div>
                          <div class="value common-value">{{ wbMentalPatientBean.currentAddress || '暂无' }}</div>
                        </div>
                        <div class="info-wrap f1">
                          <div class="label common-lable">管辖派出所</div>
                          <div class="value common-value">{{ wbMentalPatientBean.policeAgencyName || '暂无' }}</div>
                        </div>
                      </div>

                      <div class="flex">
                        <div class="info-wrap f1">
                          <div class="label common-lable">所属责任区</div>
                          <div class="value common-value">
                            {{ wbMentalPatientBean.policeJurisdictionName || '暂无' }}
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <div id="caring-anchor">
                    <div style="position: relative; padding: 10px 0">
                      <div class="common-title">
                        <div class="icon"></div>
                        <div class="content">爱心关怀小组</div>
                      </div>
                      <div class="add-btn cursor" style="position: absolute; height: 40px" @click="handelCaring">
                        + 新增
                      </div>
                    </div>

                    <a-table
                      rowKey="id"
                      class="wearing-table"
                      :columns="careColumns"
                      :dataSource="wbHelpInfoList"
                      :pagination="false"
                    >
                      <template slot="isResponsible" slot-scope="text, records">
                        <a-switch
                          v-model="records.status"
                          @change="
                            () => {
                              handleChangeResponsible(records)
                            }
                          "
                        />
                      </template>
                      <template slot="action" slot-scope="records">
                        <span class="operation deatil-color" @click="handleUnbind(records)">解绑</span>
                      </template>
                    </a-table>
                  </div>

                  <div id="medicine-anchor">
                    <div class="common-title">
                      <div class="icon"></div>
                      <div class="content">吃药记录</div>
                    </div>
                    <medication-record />
                  </div>

                  <div id="disease-anchor">
                    <div class="common-title">
                      <div class="icon"></div>
                      <div class="content">行为（发病）记录</div>
                    </div>
                    <disease-incidence-record />
                  </div>

                  <div id="caring-record-anchor">
                    <div class="common-title">
                      <div class="icon"></div>
                      <div class="content">关怀记录</div>
                    </div>
                    <div style="display: flex">
                      <a-table
                        v-for="(item, index) in careRecordColumns"
                        :key="index"
                        rowKey="id"
                        class="wearing-table"
                        :columns="[item]"
                        :dataSource="item.value"
                        :pagination="false"
                        :style="{ width: '270px' }"
                      >
                        <template slot="action" slot-scope="records"> </template>
                      </a-table>
                    </div>
                  </div>

                  <div id="device-anchor">
                    <div class="common-title">
                      <div class="icon"></div>
                      <div class="content">设备信息</div>
                    </div>

                    <a-table
                      rowKey="id"
                      class="wearing-table"
                      :columns="equipmentColumns"
                      :dataSource="deviceInfoList"
                      :pagination="false"
                    >
                      <template slot="action" slot-scope="records">
                        <span class="operation deatil-color" @click="handleChange(records)">更换</span>
                      </template>
                    </a-table>
                  </div>

                  <div id="device-warning-anchor">
                    <div class="common-title">
                      <div class="icon"></div>
                      <div class="content">设备预警与处置</div>
                    </div>
                    <equipment-warning ref="equipmentWarningRef" />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </a-col>
    </a-row>
    <select-caring-person ref="selectCaringPersonRef" @success="onSelectSuccess" />
    <allMessage
      ref="allMessage"
      :title="confirmTitle"
      :content="confirmContent"
      :publicVisible="publicVisible"
      @cancel="publicVisible = false"
      @tipMessage="tipMessage"
    ></allMessage>
  </div>
</template>

<script lang="jsx">
import leftTree from '@/components/leftTree'
import topTitle from '@/components/topTitle'
import list from './modules/list'
import Add from './modules/add'
import { getCommunityList, mentalpatientDeviceDetails } from '@/api/api'
import CallLogList from './modules/callLogList'
import SelectCaringPerson from './modules/selectCaringPerson.vue'
import {
  DiseaseIncidenceRecordmentalpatientBingding,
  setResponsibl,
  MedicationRecordePerson,
  mentalpatientBingding,
  setResponsiblePerson,
} from '../../../api/api'
import allMessage from '@/components/allMessage'
import MedicationRecord from './modules/medicationRecord.vue'
import DiseaseIncidenceRecord from './modules/diseaseIncidenceRecord.vue'
import EquipmentWarning from './modules/equipmentWarning.vue'
import crumbs from '@/components/crumbs'

export default {
  name: 'pringing',
  components: {
    leftTree,
    topTitle,
    list,
    Add,
    CallLogList,
    SelectCaringPerson,
    allMessage,
    MedicationRecord,
    DiseaseIncidenceRecord,
    EquipmentWarning,
    crumbs,
  },
  data() {
    return {
      content: [
        {
          title: '患者档案',
          path: '/humanisticConcern/patientProfile/index',
        },
        {
          title: '患者详情',
        },
      ],
      activeKey: 0,
      key: '',
      selectedKey: '',
      addRef: null,
      tabList: [
        {
          title: 'basic-anchor',
          name: '基础信息',
        },
        {
          title: 'caring-anchor',
          name: '关怀小组',
        },
        {
          title: 'medicine-anchor',
          name: '吃药记录',
        },
        {
          title: 'disease-anchor',
          name: '行为（发病）记录',
        },
        {
          title: 'caring-record-anchor',
          name: '关怀记录',
        },
        {
          title: 'device-anchor',
          name: '设备信息',
        },
        {
          title: 'device-warning-anchor',
          name: '设备预警与处置',
        },
      ],
      detail: {},
      careColumns: [
        {
          title: '序号',
          align: 'center',
          width: 100,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '人员类型',
          align: 'center',
          dataIndex: 'helpPersonTypeText',
          customRender: (t) => {
            return (
              <a-tooltip placement="top">
                <template slot="title">
                  <span>{t}</span>
                </template>
                <div class="ant-table-row-cell-ellipsis">{t}</div>
              </a-tooltip>
            )
          },
        },
        {
          title: '人员姓名',
          align: 'center',
          dataIndex: 'helpName',
          ellipsis: true,
          customRender: (t) => {
            return (
              <a-tooltip placement="top">
                <template slot="title">
                  <span>{t}</span>
                </template>
                <div class="ant-table-row-cell-ellipsis">{t}</div>
              </a-tooltip>
            )
          },
        },
        {
          title: '设为主要负责人',
          align: 'center',
          dataIndex: 'isResponsible',
          ellipsis: true,
          width: 140,
          scopedSlots: { customRender: 'isResponsible' },
        },
        {
          title: '身份证号码',
          align: 'center',
          dataIndex: 'helpIdCard',
          ellipsis: true,
          customRender: (t) => {
            return (
              <a-tooltip placement="top">
                <template slot="title">
                  <span>{t}</span>
                </template>
                <div class="ant-table-row-cell-ellipsis">{t}</div>
              </a-tooltip>
            )
          },
        },
        {
          title: '手机号码',
          align: 'center',
          dataIndex: 'helpPhone',
          ellipsis: true,
          customRender: (t) => {
            return (
              <a-tooltip placement="top">
                <template slot="title">
                  <span>{t}</span>
                </template>
                <div class="ant-table-row-cell-ellipsis">{t}</div>
              </a-tooltip>
            )
          },
        },
        {
          title: '居住地址/所属单位',
          align: 'center',
          dataIndex: 'orgName',
          ellipsis: true,
          customRender: (t) => {
            return (
              <a-tooltip placement="top">
                <template slot="title">
                  <span>{t}</span>
                </template>
                <div class="ant-table-row-cell-ellipsis">{t}</div>
              </a-tooltip>
            )
          },
        },
        {
          title: '是否下发',
          align: 'center',
          dataIndex: 'issuedStatus',
          customRender(t) {
            return t == 1 ? '已下发' : '未下发'
          },
          ellipsis: true,
        },
        {
          title: '绑定时间',
          align: 'center',
          dataIndex: 'createTime',
          ellipsis: true,
          customRender: (t) => {
            return (
              <a-tooltip placement="top">
                <template slot="title">
                  <span>{t}</span>
                </template>
                <div class="ant-table-row-cell-ellipsis">{t}</div>
              </a-tooltip>
            )
          },
        },
        {
          title: '操作',
          scopedSlots: { customRender: 'action' },
          ellipsis: true,
          align: 'center',
          width: 200,
          fixed: 'right',
        },
      ],
      careRecordColumns: [],
      wearingPersonnelList: [],
      abnormalDataColumns: [
        {
          title: '序号',
          align: 'center',
          width: 100,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          title: '类型',
          align: 'center',
          dataIndex: 'fHjdzQhnxxdz',
        },
        {
          title: '发生时间',
          align: 'center',
          dataIndex: 'fYfzgx',
          ellipsis: true,
        },
        {
          title: '发生地点',
          align: 'center',
          dataIndex: 'policeAgencyName',
          ellipsis: true,
        },
      ],
      equipmentColumns: [
        {
          title: '序号',
          align: 'center',
          width: 100,
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        // {
        //   title: '设备类型',
        //   align: 'center',
        //   dataIndex: 'deviceType',
        // },
        {
          title: '设备IMEI码',
          align: 'center',
          dataIndex: 'imei',
          ellipsis: true,
        },
        {
          title: '设备状态',
          align: 'center',
          dataIndex: 'onLine',
          ellipsis: true,
          customRender: (t) => {
            return t == 1 ? '在线' : '离线'
          },
        },
        {
          title: '当前位置',
          align: 'center',
          dataIndex: 'address',
          ellipsis: true,
        },
      ],
      timeType: 'day',
      map: null,
      markerList: [],
      drawing: false,
      ploygonList: [],
      selectCaringPersonRef: null,
      wbMentalPatientBean: {},
      wbDeviceInfoBean: {},
      wbHelpInfoList: [],
      deviceInfoList: [],
      tableWidth: 0,
      confirmTitle: '',
      confirmContent: '',
      allMessage: null,
      publicVisible: false,
    }
  },
  mounted() {
    this.activeKey = this.$route.query.activeKey ? this.$route.query.activeKey : 0
    // this.initMap()
    this.initData()
  },
  methods: {
    initData() {
      mentalpatientDeviceDetails({
        id: this.$route.query.id,
      }).then((res) => {
        const { wbMentalPatientBean, wbHelpInfoList, wbDeviceInfoBean } = res.result
        this.wbMentalPatientBean = wbMentalPatientBean
        this.wbHelpInfoList = wbHelpInfoList.map((item) => {
          return {
            ...item,
            status: item.isResponsible === '1' ? true : false,
          }
        })
        this.wearingPersonnelList = wbHelpInfoList
        // 按照 type 来进行分类
        let groupWithPersonType = this.wbHelpInfoList.reduce((acc, curr) => {
          if (acc[curr.helpPersonType]) {
            acc[curr.helpPersonType].value.push(curr)
          } else {
            acc[curr.helpPersonType] = {}
            acc[curr.helpPersonType].title = curr.helpPersonTypeText
            acc[curr.helpPersonType].value = []
            acc[curr.helpPersonType].value.push(curr)
          }
          return acc
        }, {})

        this.careRecordColumns = Object.values(groupWithPersonType).map((item) => {
          this.tableWidth += 270
          return {
            title: item.title,
            width: 200,
            children: [
              {
                title: '姓名',
                dataIndex: 'helpName',
                key: 'helpName',
                width: 84,
                align: 'center',
                scopedSlots: { customRender: 'alreadyTotalSlot1' }, // 表格template插槽内容
              },
              {
                title: '打卡数',
                dataIndex: 'count',
                key: 'count',
                width: 84,
                align: 'center',
              },
            ],
            value: item.value,
          }
        })

        let keys = Object.keys(groupWithPersonType)
        if (!keys.length) {
          this.tableWidth = '100%'
        } else {
          this.tableWidth += 'px'
        }
        this.wbDeviceInfoBean = wbDeviceInfoBean
        this.deviceInfoList = [wbDeviceInfoBean]

        // 再请求处置列表
        this.$refs.equipmentWarningRef.extendParams.imei = wbDeviceInfoBean.imei
        this.$refs.equipmentWarningRef.loadData(1)
      })
    },
    handelClick(event) {
      this.activeKey = event
      this.searchTableData()
    },
    onTreeSelected(selectedKeys) {
      this.selectedKey = Array.isArray(selectedKeys) ? selectedKeys[0] : ''
      if (this.selectedKey) {
        this.searchTableData()
        this.loadDataWithTree({
          policeAgencyId: this.selectedKey,
        })
      }
    },
    searchTableData() {
      this.$nextTick(() => {
        // 调用各个组件的 search 方法
        this.$refs.listRef.searchQuery()
      })
    },
    handleChange() {},
    onChange() {},
    initMap() {
      this.map = new AMap.Map('map-box', {
        resizeEnable: true,
        center: [116.397428, 39.90923],
        zoom: 13,
      })
      this.map.on('click', (e) => {
        const position = [e.lnglat.lng, e.lnglat.lat]
        //如果没有 marker 则添加 ，否则新增
        this.addMarker(this.map, position)
      })
    },
    addMarker(map, position) {
      var marker = new AMap.Marker({
        position: position,
        icon: new AMap.Icon({
          image: '//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png',
          size: new AMap.Size(25, 34),
          imageSize: new AMap.Size(25, 34), //图标大小
        }),
        anchor: 'bottom-center',
        offset: new AMap.Pixel(0, 0),
      })

      marker.setMap(map)

      // 设置鼠标划过点标记显示的文字提示
      marker.setTitle('我是marker的title')

      // 设置label标签
      // label默认蓝框白底左上角显示，样式className为：amap-marker-label
      marker.setLabel({
        direction: 'top',
        offset: new AMap.Pixel(0, 0), //设置文本标注偏移量
        content: `<div class='info'>点${this.markerList.length + 1}</div>`, //设置文本标注内容
      })

      this.markerList.push(marker)
    },
    // 开启鼠标绘制
    handleStartMouse() {
      this.drawing = true
    },
    // 四个点确定
    handleConfirmPoint() {
      if (this.markerList.length > 4) {
        this.$message.warning('绘制点数量不能超过4个！')
        return
      }
      let ploygonList = this.markerList.map((item) => {
        return item.getPosition()
      })
      this.addPloygon(ploygonList)
    },
    // 清除所有点
    handleClearPoint() {
      this.markerList.forEach((marker) => {
        marker.setMap(null)
      })
      this.markerList = []

      // 顺便移除之前的覆盖物
      this.ploygonList.forEach((ploygonInstance) => {
        this.map.remove(ploygonInstance)
      })
    },

    // 添加覆盖物
    addPloygon(polygonPath) {
      var polygon = new AMap.Polygon({
        path: polygonPath,
      })
      this.ploygonList.push(polygon)
      this.map.add([polygon])
    },
    handelCaring() {
      this.$refs.selectCaringPersonRef.show()
    },
    onSelectSuccess() {
      this.initData()
    },
    handleChangeResponsible(records) {
      setResponsiblePerson({
        helpId: records.id,
        mentalPatientPersonId: this.$route.query.id,
      })
        .then((res) => {
          this.$message.success(res.message)
          this.initData()
        })
        .catch(() => {
          // records.status = false
        })
    },
    handleUnbind(records) {
      this.confirmTitle = '解绑'
      this.confirmContent = '请确认是否解绑？'
      this.publicVisible = true
      this.$refs.allMessage.show(records)
    },
    tipMessage(records) {
      mentalpatientBingding({
        helpId: records.id,
        mentalPatientPersonId: this.$route.query.id,
        type: 2,
      }).then((res) => {
        this.publicVisible = false
        this.$message.success(res.message)
        this.initData()
      })
    },
    getCurrentAnchor() {
      return '#basic-anchor'
    },
    getContainerBack() {
      return document.querySelector('.right-content')
    },
  },
}
</script>
<style lang="less" scoped>
.visitor-index {
  width: 100%;
  height: 100%;
  .pageInfo {
    width: 100%;
    height: 100%;
    display: flex;
    .tab-info {
      width: 160px;
      height: 100%;
      background: var(--theme-container-bg);
      border-radius: 4px 4px 4px 4px;
      padding-top: 23px;
      margin-right: 8px;
      flex-shrink: 0;
      /deep/ .anchor-wrapper {
        background: unset;
        .ant-anchor {
          .ant-anchor-ink {
            &:nth-child(1) {
              display: none;
            }
          }
          .ant-anchor-link-title {
            font-weight: 500;
            font-size: 5rpx;
            color: #abd5ff;
            text-align: center;
            margin-bottom: 15px;
          }
          .ant-anchor-link-active {
            .ant-anchor-link-title {
              color: #fff;
            }
          }
        }
      }
    }
    .right-content {
      flex: 1;
      background: var(--theme-container-bg);
      padding: 21px 24px;
      overflow: auto;
      .common-title {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        margin-top: 12px;

        .icon {
          width: 6px;
          height: 6px;
          background: #abd5ff;
          border-radius: 50%;
          margin-right: 7px;
        }
        .content {
          font-weight: 500;
          font-size: 14px;
          color: var(--theme-tab-text-color);
        }
      }

      .wearing-table {
        /deep/.ant-table-thead > tr > th {
          height: 46px;
          background: #0946a8;
          border-radius: 0px 0px 0px 0px;
          border: 1px solid #0855cc;
          font-weight: 500;
          font-size: 14px;
          color: #8fbbff;
          border-right: 0;
          &:last-child {
            border-right: 1px solid #0855cc;
          }
        }
        /deep/ .ant-table-thead {
          border-right: 1px solid #0855cc;
        }
        /deep/ .ant-table-tbody .ant-table-row td {
          background: #07429e;
          border-radius: 0px 0px 0px 0px;
          border: 1px solid #0855cc;
          color: #ffffff;
          border-right: 0;
          border-top: 0;
        }

        /deep/.ant-table-placeholder {
          background-color: var(--theme-container-bg);
          border: 1px solid #0855cc;
          border-top: 0;
          .ant-empty-normal {
            color: #fff;
          }
        }
      }
      .content-wrapper {
        border-top: 1px solid #0855cc;
        border-left: 1px solid #0855cc;

        .info-wrap {
          display: flex;
          align-items: stretch;
          border-bottom: 1px solid #0855cc;
          border-right: 1px solid #0855cc;

          .label {
            background: #0946a8;
            width: 160px;
            padding: 14px 20px;
            font-weight: 500;
            font-size: 14px;
            color: #8fbbff;
            border-right: 1px solid #0855cc;
          }
          .value {
            font-weight: 400;
            font-size: 14px;
            color: #ffffff;
            padding: 14px 20px;
          }
        }
      }

      .time-select {
        display: flex;
        .time-btn-style {
          .ant-radio-button-wrapper {
            background: #06409a;
            border: 1px solid #0855cc;
            font-weight: 500;
            font-size: 14px;
            color: #8fbbff;
            &::before {
              width: 0;
            }
          }
          .ant-radio-button-wrapper-checked {
            background: #1970f6;
            border: 1px solid #1970f6;
          }
        }
        .time-range {
          width: 310px !important;
          margin-left: 8px;
        }
      }
    }
  }
  .title-wrapper-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .l-w_content {
    margin-left: 2px;
    height: calc(100% - 50px);
  }
  .right-inner-box {
    width: 100%;
    height: 100%;
    position: relative;
    #map-box {
      width: 100%;
      height: 100%;
    }
    .button-group {
      position: absolute;
      right: 10px;
      z-index: 10;
      padding-top: 6px;
      .i-btn {
        margin-right: 6px;
      }
    }
  }
}
</style>
